import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core';

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  constructor(private readonly httpAdapterHost: HttpAdapterHost) {}

  catch(exception: unknown, host: ArgumentsHost): void {
    const { httpAdapter } = this.httpAdapterHost;

    const ctx = host.switchToHttp();

    const httpStatus =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;

    const message =
      exception instanceof HttpException
        ? exception.getResponse()
        : (exception as any).message || 'Internal server error';

    const responseBody = {
      code: 500,
      message: this.getMessage(message),
      data: null,
    };
    console.log(responseBody.message);

    httpAdapter.reply(ctx.getResponse(), responseBody, 500);
  }
  getMessage(message: any) {
    if (typeof message === 'string') return message;
    if (Array.isArray(message.message) && message.message.length > 0)
      return String(message.message[0]);
    return JSON.stringify(message.message);
  }
}
